#include "sm2.h"
#include "sm3.h"
#include <stdio.h>
#include <stdlib.h>
#include <openssl/ec.h>
#include <openssl/pem.h>
#include <openssl/err.h>

int main() {
    // 示例：生成SM2密钥对
    EC_KEY *keypair = generate_sm2_keypair();
    if (!keypair) {
        fprintf(stderr, "Failed to generate SM2 key pair.\n");
        exit(EXIT_FAILURE);
    }

    EVP_PKEY *pub_key = EVP_PKEY_new();
    if (!pub_key) {
        EC_KEY_free(keypair);
        fprintf(stderr, "Failed to create EVP_PKEY.\n");
        exit(EXIT_FAILURE);
    }
    if (!EVP_PKEY_set1_EC_KEY(pub_key, keypair)) {
        EVP_PKEY_free(pub_key);
        EC_KEY_free(keypair);
        fprintf(stderr, "Failed to set EVP_PKEY with EC_KEY.\n");
        exit(EXIT_FAILURE);
    }

    unsigned char *plaintext = (unsigned char *)"Hello, world!";
    size_t plaintext_len = strlen((char *)plaintext);
    unsigned char *ciphertext = NULL;
    size_t ciphertext_len = 0;
    if (!sm2_encrypt(plaintext, plaintext_len, pub_key, &ciphertext, &ciphertext_len)) {
        fprintf(stderr, "SM2 encryption failed.\n");
        exit(EXIT_FAILURE);
    }

    unsigned char *decryptedtext = NULL;
    size_t decryptedtext_len = 0;
    if (!sm2_decrypt(ciphertext, ciphertext_len, keypair, &decryptedtext, &decryptedtext_len)) {
        fprintf(stderr, "SM2 decryption failed.\n");
        exit(EXIT_FAILURE);
    }

    printf("SM2 Encrypted: ");
    for (size_t i = 0; i < ciphertext_len; i++) {
        printf("%02X", ciphertext[i]);
    }
    printf("\n");
    printf("SM2 Decrypted: %s\n", decryptedtext);

    // 清理资源
    OPENSSL_free(ciphertext);
    OPENSSL_free(decryptedtext);
    EVP_PKEY_free(pub_key);
    EC_KEY_free(keypair);
    return 0;
}
